import { InputNumber, Space, Select, Button, Col, Modal, Input, message, Row, Tag, Table, Flex,Tooltip } from "ant-design-vue";
import type { TableColumnsType } from "ant-design-vue";
import { computedAsync, useVModels } from "@vueuse/core";
import { useCommonStaticOptions } from "@/hooks/useEsArticleCommon";
import { getIndexFieldApi, onCePublishArticleApi } from "@/api/esArticle";
import { ES } from "@/api/esSearch";
// 其他选项的input类型组件
export const KeywordMaxAndMinCount = defineComponent({
    props: {
        maxCount: { type: Number },
        minCount: { type: Number },
        type: { type: Number, default: 0 }
    },
    emits: ["update:maxCount", "update:minCount"],
    setup(props, { emit }) {
        const { minCount, maxCount } = useVModels(props, emit);
        const prefix = computed(() => (props.type === 0 ? "关键词" : "图片"));
        // 返回一个render函数 tsx只是h函数的简写方式
        return () => (
            <Space>
                <span>{prefix.value}最小个数</span>
                <InputNumber id="inputNumber" v-model:value={minCount.value} min={1} />
                <span style="margin-right: 10px">{prefix.value}最大个数</span>
                <InputNumber id="inputNumber" v-model:value={maxCount.value} min={1} />
            </Space>
        );
    }
});
export const InputNumberWidthAndHeight = defineComponent({
    props: {
        height: { type: Number },
        width: { type: Number },
        type: { type: Number, default: 0 }
    },
    emits: ["update:height", "update:width"],
    setup(props, { emit }) {
        const { height, width } = useVModels(props, emit);
        const prefix = computed(() => (props.type === 0 ? "画布" : "logo"));
        // 返回一个render函数 tsx只是h函数的简写方式
        return () => (
            <Space>
                <span>{prefix.value}大小</span>
                <InputNumber id="inputNumber" v-model:value={width.value} />
                <InputNumber id="inputNumber" v-model:value={height.value} />
            </Space>
        );
    }
});

// 数字区间组件
export const InputNumberRange = defineComponent({
    props: {
        minNum: { type: Number },
        maxNum: { type: Number }
    },
    emits: ["update:maxNum", "update:minNum"],
    setup(props, { emit }) {
        const { maxNum, minNum } = useVModels(props, emit);
        return () => (
            <Space tabindex="999">
                <InputNumber v-model:value={minNum.value} placeholder="最小值" min={0} />
                至
                <InputNumber v-model:value={maxNum.value} placeholder="最大值" min={0} />
            </Space>
        );
    }
});

// 生成一次性文章按钮组件
export const OncePublishArticleButton = defineComponent({
    props: ["id"],
    setup(props: { id: number }) {
        const publishNum = ref(100);
        const pcDomain = ref("");
        const columns = ref("");
        const visible = ref(false);
        const openModal = () => {
            visible.value = true;
        };
        const offModal = () => {
            visible.value = false;
        };
        const onOkFunc = () => {
            if (!columns.value || !pcDomain.value) {
                return message.error("请填写完整!");
            }
            const custom_columns = columns.value.split(",").filter(Boolean).map(Number);
            if (!custom_columns.length) {
                return message.error("栏目格式有误!");
            }
            btnLoading.value = true;
            onCePublishArticleApi({
                custom_columns: custom_columns,
                article_num: publishNum.value,
                domain: pcDomain.value,
                rule_id: props.id
            })
                .then((res) => {
                    if (res.data.code === 200) {
                        message.success("发布成功!");
                        offModal();
                        return;
                    } else {
                        message.error(res.data.msg);
                    }
                })
                .catch((err) => message.error(err.data.msg || "发布失败!"))
                .finally(() => (btnLoading.value = false));
        };
        const btnLoading = ref(false);
        return () => (
            <>
                <Button type="link" onClick={openModal}>
                    一次性发布
                </Button>
                <Modal
                    style="width:300px"
                    title="为了解决新建站缺少文章的问题"
                    v-model:open={visible.value}
                    onCancel={offModal}
                    okButtonProps={{ loading: btnLoading.value }}
                    onOk={onOkFunc}
                >
                    <Row gutter={[8, 16]}>
                        <Col span={24}>
                            <Space>
                                域名
                                <Input placeholder="发布网站" v-model:value={pcDomain.value}></Input>
                            </Space>
                        </Col>
                        <Col span={24}>
                            <Space>
                                栏目
                                <Input placeholder="自定义栏目 1,2" v-model:value={columns.value}></Input>
                            </Space>
                        </Col>
                        <Col span={24}>
                            <Space>
                                发布数
                                <InputNumber placeholder="发布数" v-model:value={publishNum.value}></InputNumber>
                            </Space>
                        </Col>
                    </Row>
                </Modal>
            </>
        );
    }
});
type SettingPublishApiFieldProps = {
    visible: boolean;
    publishApiFieldData: PostPublishApiParmas["field_data"];
    esHost: string;
    esIndex: string;
    fieldData: Record<string, string>;
};
// 设置字段
export const SettingPublishApiField = defineComponent({
    props: ["visible", "publishApiFieldData", "fieldData", "esHost", "esIndex"],
    emits: ["update:visible", "update:fieldData"],
    setup(props: SettingPublishApiFieldProps, { emit }) {
        const { visible, fieldData } = useVModels(props, emit);
        const publishApiFieldData = computed(() => props.publishApiFieldData);
        const { filterOption } = useCommonStaticOptions();
        onMounted(() => {
            if (!Object.keys(fieldData.value).length) {
                fieldData.value = Object.fromEntries(
                    publishApiFieldData.value.map((item) => {
                        return [item.value, ""];
                    })
                );
            }
        });
        const onCancel = () => (visible.value = false);
        const onOk = () => {
            for (const item of Object.values(fieldData.value)) {
                if (!item) {
                    return message.error("请填写完整!");
                }
            }
            visible.value = false;
        };
        // es索引字段列表
        const esIndexFields = computedAsync<SelectOption>(() => {
            return new Promise((resolve) => {
                if (visible.value) {
                    getIndexFieldApi({ index_name: props.esIndex, es_host: props.esHost }).then((res) => {
                        if (res.data.code === 200) {
                            resolve(res.data.data.filter((item: any) => item.type == "text" && !item.value.includes(".")));
                        }
                    });
                } else {
                    resolve([]);
                }
            });
        });
        const span = (v:string)=>{
            return (
                <span style="min-width:100px;margin-right:5px">{v}</span>
            )
        }
        const reg = /<.*?>/
        return () => (
            <>
                <Modal title="设置发布接口字段" v-model:open={visible.value} style="width:600px" onCancel={onCancel} onOk={onOk}>
                    <br />
                    {publishApiFieldData.value &&
                        publishApiFieldData.value
                            .filter((item) => Boolean(item.label))
                            .map((item) => {
                                const isCustom = item.type === "custom";
                                return (
                                    <Flex align="center" style="margin-bottom:15px">
                                        <Tag color={isCustom ? "processing" : "default"} style="margin-left:15px">
                                            {isCustom ? "自定义" : "ES字段"}
                                        </Tag>
                                        {isCustom ? (
                                            <>
                                                {
                                                    reg.test(item.label)
                                                    ? <Tooltip title={item.label.match(reg)}>
                                                        <span style="min-width:100px;margin-right:5px">{item.label.replace(reg,'')}</span>
                                                    </Tooltip> :  span(item.label)
                                                }
                                                <Input
                                                    placeholder="根据label输入值"
                                                    style="max-width:200px"
                                                    v-model:value={fieldData.value[item.value]}
                                                ></Input>
                                            </>
                                        ) : (
                                            <>
                                                {span(item.label)}
                                                <Select
                                                    style="width:140px"
                                                    v-model:value={fieldData.value[item.value]}
                                                    options={esIndexFields.value}
                                                    filterOption={filterOption}
                                                    showSearch
                                                ></Select>
                                            </>
                                        )}
                                    </Flex>
                                );
                            })}
                </Modal>
            </>
        );
    }
});

type DayPublishedArticleInfoProps = {
    rule_name: string;
};
// 今日已发文章信息
export const DayPublishedArticleInfo = defineComponent({
    props: ["rule_name"],
    setup(props: DayPublishedArticleInfoProps) {
        const columns: TableColumnsType = [
            {
                dataIndex: "key",
                title: "域名",
                width: 200
            },
            {
                dataIndex: "doc_count",
                title: "今日发布成功数",
                width: 150,
                sorter: (a: any, b: any) => a.doc_count - b.doc_count
            }
        ];
        const getInfo = () => {
            const es = new ES("90");
            const date = new Date();
            const month = date.getMonth() + 1;
            const day = date.getDate();
            const today = `${date.getFullYear()}-${month < 10 ? `0` + month : month}-${day < 10 ? `0` + day : day}`;
            es.search("article_published_*", {
                query: {
                    bool: {
                        must: [
                            {
                                term: {
                                    "rule_name.keyword": props.rule_name
                                }
                            },
                            {
                                term: {
                                    status: 1
                                }
                            },
                            {
                                range: {
                                    "@timestamp": {
                                        lt: "now",
                                        gte: today
                                    }
                                }
                            }
                        ]
                    }
                },
                aggs: {
                    group_by_tags: {
                        terms: {
                            field: "domain.keyword",
                            size: 10000
                        }
                    }
                },
                size: 0
            }).then((res) => {
                dataSource.value = res.data.data.aggregations.group_by_tags.buckets;
            });
        };
        watch(() => props.rule_name, getInfo);
        const dataSource = ref([]);
        onMounted(() => {
            getInfo();
        });
        return () => (
            <>
                <br />
                <Table style="width:350px" size={"small"} columns={columns} bordered data-source={dataSource.value}></Table>
            </>
        );
    }
});
